package baseAPI;

import java.sql.*;

public class Database{
    private Connection connection;

    public Database(String ip, String sqlName, String user, String password){//构造函数，需要说明ip,数据库名,用户名和密码
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://" + ip + ":3306/" + sqlName, user, password);
        }catch(ClassNotFoundException ex){
            System.out.print("classNotFound");
        }catch(SQLException ex){
            System.out.print("SQLException_Construct");
        }
    }

    public ResultSet select(String select, String table){//查询语句(不带where)
        try {
            return connection.prepareStatement("select " + select + " from " + table).executeQuery();
        } catch (SQLException ex) {
            System.out.print("SQLException_Select");
            return null;
        }
    }

    public ResultSet select(String select, String table, String where){//查询语句(带where)
        try {
            return connection.prepareStatement("select " + select + " from " + table + " where " +where).executeQuery();
        } catch (SQLException ex) {
            System.out.print("SQLException_Select");
            return null;
        }
    }

    public void insert(String table, String values){//插入语句
        try {
            connection.prepareStatement("insert into " + table + " values(" + values +")").executeUpdate();
        } catch (SQLException ex) {
            System.out.print("SQLException_Insert");
        }
    }

    public void delete(String table, String where){//删除语句
        try {
            connection.prepareStatement("delete from " + table + " where " + where).executeUpdate();
        } catch (SQLException ex) {
            System.out.print("SQLException_Delete");
        }
    }

    public void update(String table, String key, String value, String where){//修改语句
        try {
            connection.prepareStatement("update " + table + " set " + key + " = " + value  + " where " + where).executeUpdate();
        } catch (SQLException ex) {
            System.out.print("SQLException_Update");
        }
    }
}
